package chapter04.udf;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

public class MyStringLength extends GenericUDF {
    @Override
    public ObjectInspector initialize(ObjectInspector[] objectInspectors) throws UDFArgumentException {
        // sentence args amount
        if (objectInspectors.length != 1) {
            new UDFArgumentLengthException("Input Args Length Error("+ objectInspectors.length +")!");
        }

        // sentence args type
        if (!objectInspectors[0].getCategory().equals(ObjectInspector.Category.PRIMITIVE)) {
            throw new UDFArgumentTypeException(0, "Input Args Type Error!");
        }

        // return int type, need to return int type of object inspector
        return PrimitiveObjectInspectorFactory.javaIntObjectInspector;
    }

    @Override
    public Object evaluate(DeferredObject[] deferredObjects) throws HiveException {
        // logic transport
        Object object = deferredObjects[0].get();
        if (object == null) {
            return 0;
        }

        return object.toString().length();
    }

    @Override
    public String getDisplayString(String[] strings) {
        // explain -- task planing need observe string
        return "";
    }
}
